<?php

namespace app\common\model\order;

use app\common\model\goods\Cart;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\ScoreLog;
use app\common\model\server\Goods;
use app\common\model\user\Address;
use app\common\model\user\Level;
use think\Model;


class Order extends Model
{





    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_type_text',
        'status_text',
        'paytime_text',
        'servertime_text',
        'canceltime_text',
        'taketime_text',
        'createtime_text',
    ];



    public function getPayTypeList()
    {
        return ['1' => __('Pay_type 1')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '10' => __('Status 10'), '20' => __('Status 20'), '30' => __('Status 30'), '40' => __('Status 40'), '-1' => __('Status -1')];
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getServertimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['servertime']) ? $data['servertime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCanceltimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setServertimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setTaketimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function info()
    {
        return $this->hasMany('app\common\model\order\Goods', 'order_id', 'id');
    }
    public function enter()
    {
        return $this->belongsTo('app\common\model\user\Enter', 'employee_id', 'user_id', [], 'LEFT')->setEagerlyType(0);
    }


    public function employee()
    {
        return $this->belongsTo('app\common\model\User', 'employee_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function address()
    {
        return $this->belongsTo('app\common\model\user\Address', 'address_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 预下单
     */
    public static function yuOrder($data)
    {
        extract($data);

        bcscale(2);
        //合计金额
        $data['total_money'] = $data['pay_money'] = array_sum(array_column($goods, 'totalMoney'));
        $data['vip_deduction'] = array_sum(array_column($goods, 'totalVipDeduction'));
        $data['num'] = array_sum(array_column($goods, 'num'));
        $data['pay_money'] = bcsub($data['pay_money'], $data['vip_deduction']);
        $data['vip_money'] = array_sum(array_column($data, 'totalVipMoney'));
        $data['point'] = $data['point_deduction'] = 0;
        // //会员优惠金额
        // if ($level_id) {
        //     $level = Level::get($level_id);
        //     if ($level && $level->discount > 0) {
        //         $discount = bcdiv($level->discount, 100);
        //         $data['vip_deduction'] = bcmul($data['total_money'], $discount);
        //         $data['pay_money'] = bcsub($data['total_money'], $data['vip_deduction']);
        //     }
        // }
        $max_deducted = config('site.max_deducted');
        if ($score > 0 && $is_point) {
            $integral_proportion = config('site.integral_proportion');
            $max_point = bcmul($max_deducted, $integral_proportion);
            if ($max_point <= $score) {
                $data['point_deduction'] = bcdiv($score, $integral_proportion, 0);
                if ($data['point_deduction'] > $max_deducted) {
                    $data['point_deduction'] = $max_deducted;
                }
                $data['point'] = $max_point;
                $data['pay_money'] = bcsub($data['pay_money'], $data['point_deduction']);
            }
        }
        //地址信息
        if (isset($address_id) && !empty($address_id)) {
            $addressInfo = Address::get([$address_id]);
            $data['addressInfo'] = $addressInfo;
            $data['address_id']  = $address_id;
        } else {
            $addressInfo = Address::getDefaultAddress($user_id);

            if ($addressInfo) {
                $data['addressInfo'] = $addressInfo;
                $data['address_id']  = $addressInfo['id'];
            }
        }
        $data['user_id'] = $user_id;
        return $data;
    }

    public static function addOrder($data)
    {
        extract($data);
        $product = Goods::get($goods[0]['goods_id']);
        $param = [
            'sn' => sn('order', 'sn', 'NO'),
            'category_id' => $product['category_id'],
            'province' => $addressInfo['province'],
            'city' => $addressInfo['city'],
            'area' => $addressInfo['area'],
            'address' => $addressInfo['province'] . $addressInfo['city'] . $addressInfo['area'] . $addressInfo['address'],
            'consignee' => $addressInfo['contact'],
            'phone' => $addressInfo['telephone'],
            'lng' => $addressInfo['longitude'],
            'lat' => $addressInfo['latitude'],
        ];
        $array = array_merge($data, $param);
        $model = new self($array);
        $res = $model->allowField(true)->save();
        if ($res) {
            $arr = [];
            foreach ($goods as $v) {
                array_push($arr, [
                    'order_id' => $model->id,
                    'goods_id' => $v->goods_id,
                    'goods_num' => $v->num,
                    'goods_name' => $v->goods->title,
                    'image' => $v->goods->image,
                    'goods_price' => $v->goods->pay_money,
                    'total_price' => $v->totalMoney,
                ]);
                Goods::where('id', $v->goods_id)->inc('num', $v->num)->update();
            }
            $goods = new OrderGoods();
            $goods->saveAll($arr);
            Cart::where('type', $add_type)->delete();
        }
        if ($data['point'] > 0) {
            ScoreLog::income($data['user_id'], $data['point'], 2, 200, $model->sn);
        }
        return $model->id;
    }
}
